package com.jzg.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.dragonsoft.node.adapter.comm.RbspCall;
import com.dragonsoft.node.adapter.comm.RbspConsts;
import com.dragonsoft.node.adapter.comm.RbspService;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jzg.common.constant.ArchiveStage;
import com.jzg.common.model.biz.Cab;
import com.jzg.common.model.biz.CabCard;
import com.jzg.common.model.biz.CabModuleBoard;
import com.jzg.common.model.biz.CabStore;
import com.jzg.common.model.biz.CabStoreTemp;
import com.jzg.common.model.biz.CabStoreUser;
import com.jzg.common.model.biz.CabUser;
import com.jzg.common.model.sys.SysOrg;
import com.jzg.common.render.ArchiveWarning;
import com.jzg.common.render.Criminal;
import com.jzg.common.render.Result;
import com.jzg.common.render.Rotation;
import com.jzg.common.render.Store;

import net.sf.json.JSONObject;

@SuppressWarnings("unused")
public class CaseUtil {

	protected final static Log log = Log.getLog(CaseUtil.class);

	private static String CHINA_CASE_URL = PropKit.use("app-config-dev.txt").get("CHINA_CASE_URL");
	private static String CHINA_CASE_CLINETID = PropKit.use("app-config-dev.txt").get("CHINA_CASE_CLINETID");

	// 案件基本信息
	private static String CHINA_CASE_INFO_SEVICEID = PropKit.use("app-config-dev.txt").get("CHINA_CASE_INFO_SEVICEID");
	private static String CHINA_CASE_INFO_SHAREDATA = PropKit.use("app-config-dev.txt")
			.get("CHINA_CASE_INFO_SHAREDATA");

	// 违法犯罪嫌疑人和案件关联表
	private static String CHINA_CASE_AND_SUSPENSE_SEVICEID = PropKit.use("app-config-dev.txt")
			.get("CHINA_CASE_AND_SUSPENSE_SEVICEID");
	private static String CHINA_CASE_AND_SUSPENSE_SHAREDATA = PropKit.use("app-config-dev.txt")
			.get("CHINA_CASE_AND_SUSPENSE_SHAREDATA");

	// 违法犯罪嫌疑人
	private static String CHINA_CASE_SUSPENSE_SEVICEID = PropKit.use("app-config-dev.txt")
			.get("CHINA_CASE_SUSPENSE_SEVICEID");
	private static String CHINA_CASE_SUSPENSE_SHAREDATA = PropKit.use("app-config-dev.txt")
			.get("CHINA_CASE_SUSPENSE_SHAREDATA");

	private static String CHINA_CASE_USER_DEPT = PropKit.use("app-config-dev.txt").get("CHINA_CASE_USER_DEPT");
	private static String CHINA_CASE_USER_NAME = PropKit.use("app-config-dev.txt").get("CHINA_CASE_USER_NAME");
	private static String CHINA_CASE_USER_ID = PropKit.use("app-config-dev.txt").get("CHINA_CASE_USER_ID");

	public static String queryCaseInfo(String ajbh) {
		String res = "";
		try {
			String condition = String.format("ajbh='%s'", ajbh);
			RbspService service = new RbspService(CHINA_CASE_CLINETID, CHINA_CASE_INFO_SEVICEID);
			service.setUserCardId(CHINA_CASE_USER_ID);// 身份证号
			service.setUserDept(CHINA_CASE_USER_DEPT);
			service.setUserName(CHINA_CASE_USER_NAME);// 姓名
			RbspCall call = service.createCall();
			call.setUrl(CHINA_CASE_URL);
			call.setMethod(RbspConsts.METHOD_QUERY);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("DataObjectCode", CHINA_CASE_INFO_SHAREDATA);// 共享数据集
			params.put("InfoCodeMode", "1");
			params.put("Condition", condition);
			params.put("RequiredItems",
					new String[] { "ajbh", "ajmc", "ajlb", "ajlbdm", "ajlbmc", "ajfadwmc", "ajgsdwdm", "ajgxdwmc",
							"ajssdwjbdm", "ajsxdm", "ajsxmc", "ajzt", "asjfsjssj", "asjfskssj", "asjjsry_lxdm", "ay", "bar",
							"bar_lxdh", "bar_mjbh", "bldw_gajgmc", "fad_xz", "fxasj_fxsj", "glbm_gajgjgdm", "gsdwmc",
							"jyaq", "slsj" });// 查询所需返回的结果集
			res = call.invoke(params);
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		return res;
	}

	// 拉取案件信息
	public static void caseInfo() {

		List<CabStore> cabStores = CabStore.dao.find("select * from " + CabStore.TABLE_NAME + " where isSend='0' ");
		if (cabStores != null && cabStores.size() > 0) {
			for (CabStore cabStore : cabStores) {

				Cab cab = Cab.dao.findById(cabStore.getCabId());
				if (cab != null) {

					SysOrg sysOrg = SysOrg.dao.findById(cab.getOrgId());

					String bmbm = sysOrg == null ? "" : sysOrg.getCODE();

					CabUser cabUser = CabUser.dao.findFirst(
							"select * from " + CabUser.TABLE_NAME + " where cabId=? "
									+ " and userId in (select userId from " + CabStoreUser.TABLE_NAME + " where cabId='"
									+ cab.getId() + "' and storeId='" + cabStore.getId() + "' and src='1') ",
							cab.getId());

					Rotation rotation = new Rotation();
					rotation.setAjbh(cabStore.getId());
					rotation.setBmbm(bmbm);
					rotation.setRoleKey("");
					rotation.setAjlbdm("");
					rotation.setAy("");
					rotation.setAjgsdwdm("");
					rotation.setsHost("");
					rotation.setsHost_Tel("");

					if (cabUser != null) {
						if (StrKit.equals("530103", bmbm) && cabUser.getRoleKey().contains("all")) {
							rotation.setRoleKey("Cabinet-NQ-Leader");
						}
					}

					String strReturns = "";
					strReturns = queryCaseInfo(cabStore.getId());
					if (StrUtil.isBlank(strReturns)) {
						// 分局柜子轮案
						if (StrKit.equals("53010305", rotation.getBmbm())) {
							sendCaseInfo(cabStore, rotation);
						}
						return;
					}

					try {
						String[][] resultArys = null;
						Document doc = DocumentHelper.parseText(strReturns);
						// 获取Row节点集合
						List<?> list = doc.selectNodes("RBSPMessage/Method/Items/Item/Value/Row");
						// 判断节点是否为空同时节点大于2
						if (list != null && list.size() > 2) {
							// 获取第一个Row节点
							Element stateElement = (Element) list.get(0);
							// 获取返回数据状态
							String state = ((Element) stateElement.elements().get(0)).getText();
							if (state.equalsIgnoreCase("000")) {// 状态等于000代表结果返回正常
								Element fieldElement = (Element) list.get(1);
								// 初始化二维数组
								resultArys = new String[list.size() - 2][fieldElement.elements().size()];
								for (int i = 2; i < list.size(); i++) {
									Element data = (Element) list.get(i);
									List<?> fields = data.elements();
									for (int j = 0; j < fields.size(); j++) {
										Element tmpE = (Element) fields.get(j);
										// 二维数组赋值
										resultArys[i - 2][j] = tmpE.getText();
									}
								}
							}
						}

						if (resultArys != null) {
							if (resultArys.length > 0) {
								String[] dataRow = resultArys[0];

								if (StrKit.isBlank(dataRow[0])) {
									return;
								}
								cabStore.setJyaq(dataRow[24]);
								cabStore.update();

								if (!StrKit.isBlank(dataRow[3])) {
									rotation.setAjlbdm(dataRow[3]);
								}
								if (!StrKit.isBlank(dataRow[15])) {
									rotation.setAy(strReturns);
								}
								if (!StrKit.isBlank(dataRow[6])) {
									rotation.setAjgsdwdm(dataRow[6]);
								}
								if (!StrKit.isBlank(dataRow[16])) {
									rotation.setsHost(dataRow[16]);
								}

								if (!StrKit.isBlank(dataRow[17])) {
									rotation.setsHost_Tel(dataRow[17]);
								}
								sendCaseInfo(cabStore, rotation);
							} else {
								// 分局柜子轮案
								if (StrKit.equals("530103", rotation.getBmbm())) { 
									sendCaseInfo(cabStore, rotation);
								}
							}
						} else {
							// 分局柜子轮案
							if (StrKit.equals("530103", rotation.getBmbm())) {
								sendCaseInfo(cabStore, rotation);
							}
						}
					} catch (Exception e) {
						log.info("===================轮案接口异常！===================【" + e.getMessage() + "】");
					}

				}

			}
		}

	}

	public static void sendCaseInfo(CabStore cabStore, Rotation rotation) {

		Map<String, Object> caseMap = new HashMap<String, Object>();
		caseMap.put("Year", "");
		caseMap.put("Sequence", "");
		caseMap.put("SNO_", rotation.getAjbh());
		caseMap.put("CaseType", rotation.getAjlbdm());
		caseMap.put("CaseTypeName", rotation.getAy());
		caseMap.put("IsGroup", "0");
		caseMap.put("OfficeId", rotation.getAjgsdwdm());
		caseMap.put("SHost", rotation.getsHost());
		caseMap.put("SHost_Tel", rotation.getsHost_Tel());
		caseMap.put("InputId", "jz");// 警宗平台
		caseMap.put("Relation", "");
		caseMap.put("Nfrom", rotation.getBmbm());
		caseMap.put("Auth", rotation.getRoleKey());
		log.info("==================开始轮案===========" + JsonKit.toJson(caseMap));
		Result result = HttpUtil.doPostForForm(HttpUtil.CASE_HTTP_URL + "/InsertCaseInfo.ashx", caseMap);
		log.info("==================轮案返回===============" + result);
		if ((boolean) result.getCode()) {
			JSONObject jsonDatas = JSONObject.fromObject(result.getData());
			if (StrKit.equals("1", jsonDatas.getString("code"))) {
				cabStore.setIsSend("1");
				cabStore.update();
				//返回轮案人员 添加biz_cab_store_user表
				if(jsonDatas.containsKey("userId") && !StrKit.isBlank(jsonDatas.getString("userId"))) {
					String userId = jsonDatas.getString("userId");
					CabStoreUser cabStoreUser = CabStoreUser.dao.findFirst("select * from "+CabStoreUser.TABLE_NAME+" where cabId=? and storeId=? and userId=? ",cabStore.getCabId(),cabStore.getId(),userId);
					if(cabStoreUser==null) {
						cabStoreUser = new CabStoreUser();
						cabStoreUser.setId(UuidUtil.getUUID());
						cabStoreUser.setCabId(cabStore.getCabId());
						cabStoreUser.setStoreId(cabStore.getId());
						cabStoreUser.setUserId(userId);
						cabStoreUser.setType("1");
						cabStoreUser.setSrc("0");
						cabStoreUser.save();
					}
				}
				
			}
		}
	}

	/**
	 * 查询柜子案件状态
	 * 
	 * @param caseNo
	 * @return
	 */
	public static String getCaseStatusForDep(SysOrg org, String caseNo) {
		String status = "2";
		String sql = " FROM " + CabStoreTemp.TABLE_NAME + " WHERE 1=1 AND storeId='" + caseNo + "' ";
		if (org != null) {
			if (StrKit.equals("53010305", org.getCODE())) {
				status = "1";
				sql += " AND type = '0' ";
			} else {
				sql += " AND type = '1' ";
			}
		}
		CabStoreTemp cabStoreTemp = CabStoreTemp.dao.findFirst("SELECT * " + sql);
		if (cabStoreTemp != null) {
			status = cabStoreTemp.getStatus();
		}
		return status;
	}

	/**
	 * 获取案件关联标签对应值
	 * 
	 * @param store
	 */
	public static void getStoreMapValue(String cabId,String bmbm, Store store, CabStore cabStore) {
		try {
			if (store != null && StrKit.notBlank(store.getId())) {
				List<CabCard> cards = CabCard.dao.find("select * from " + CabCard.TABLE_NAME + " where cabId=? ",cabId);
				if (cards != null && cards.size() > 0) {
					Map<String, String> mapKey = new HashMap<String, String>();
					for (CabCard card : cards) {
						mapKey.put(card.getValue(), card.getCode());
					}
					Record record = null;boolean isofffz = true;
					if(StrKit.equals("53010305", bmbm)) {
						isofffz = false;
						record = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName,t.SName fzyName, "
										+ " (select top 1 convert(varchar(100),EndTime,102) DAlarmEnd from MCabinet where Case_NO = t.SNO_ order by SendTime desc ) DAlarmEnd "
										+ " from [CASE] t where t.SNO_ = '" + cabStore.getId() + "' ");
					}else {
						record = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName from [CASE] t where t.SNO_ = '"+cabStore.getId()+"' ");
					}
					
					if (record != null) {
						String NCase = record.getStr("NId");
						store.setField1(StrKit.isBlank(record.getStr(mapKey.get("field1"))) ? "" : record.getStr(mapKey.get("field1")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField2(StrKit.isBlank(record.getStr(mapKey.get("field2"))) ? "" : record.getStr(mapKey.get("field2")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField3(StrKit.isBlank(record.getStr(mapKey.get("field3"))) ? "" : record.getStr(mapKey.get("field3")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField4(StrKit.isBlank(record.getStr(mapKey.get("field4"))) ? "" : record.getStr(mapKey.get("field4")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField5(StrKit.isBlank(record.getStr(mapKey.get("field5"))) ? "" : record.getStr(mapKey.get("field5")).replaceAll(" ", "").replaceAll("├─", ""));

						cabStore.setField1(StrKit.isBlank(record.getStr(mapKey.get("field1"))) ? "" : record.getStr(mapKey.get("field1")).replaceAll(" ", "").replaceAll("├─", ""));
						cabStore.setField2(StrKit.isBlank(record.getStr(mapKey.get("field2"))) ? "" : record.getStr(mapKey.get("field2")).replaceAll(" ", "").replaceAll("├─", ""));
						cabStore.setField3(StrKit.isBlank(record.getStr(mapKey.get("field3"))) ? "" : record.getStr(mapKey.get("field3")).replaceAll(" ", "").replaceAll("├─", ""));
						cabStore.setField4(StrKit.isBlank(record.getStr(mapKey.get("field4"))) ? "" : record.getStr(mapKey.get("field4")).replaceAll(" ", "").replaceAll("├─", ""));
						cabStore.setField5(StrKit.isBlank(record.getStr(mapKey.get("field5"))) ? "" : record.getStr(mapKey.get("field5")).replaceAll(" ", "").replaceAll("├─", ""));
						
						if(!isofffz | StrKit.isBlank(record.getStr("DAlarmEnd"))) {
							if(mapKey.containsValue("DAlarmEnd")) {
								mapKey.forEach((key, value) -> {
									if(StrKit.equals("DAlarmEnd", value)) {
										String sqlNormalStr = "select a.SName,a.SIdentityCard,a.NMeasureType,b.DAlarmEnd from Crime a,Stage b where a.NId=b.NCrime "
												+ "	and a.NState <> '-1' and b.NState <> '-1' and b.BisCancle='0' and ( b.BIsPause is null  or b.BIsPause = '0' ) and a.NCase='"+NCase+"' ";
										List<Record> suspectListList=Db.use("plga").find(sqlNormalStr);
										String DAlarmEnd="";
										for(Record suspect:suspectListList) {
											if(!StrKit.isBlank(DAlarmEnd)) {
												SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
												try {
													Date bt=sdf.parse(suspect.getStr("DAlarmEnd"));
													Date et=sdf.parse(DAlarmEnd);
													if(bt.before(et)) {
														DAlarmEnd = suspect.getStr("DAlarmEnd");
													}
												} catch (ParseException e) {
												}
											}else {
												DAlarmEnd = suspect.getStr("DAlarmEnd");
											}
										}
										//赋值
										if(StrKit.equals("field1", key)) {
											store.setField1(DAlarmEnd);
											cabStore.setField1(DAlarmEnd);
										}
										if(StrKit.equals("field2", key)) {
											store.setField2(DAlarmEnd);
											cabStore.setField2(DAlarmEnd);
																		}
										if(StrKit.equals("field3", key)) {
											store.setField3(DAlarmEnd);
											cabStore.setField3(DAlarmEnd);
										}
										if(StrKit.equals("field4", key)) {
											store.setField4(DAlarmEnd);
											cabStore.setField4(DAlarmEnd);
										}
										if(StrKit.equals("field5", key)) {
											store.setField5(DAlarmEnd);
											cabStore.setField5(DAlarmEnd);
										}
									}
						        });
							}
						}
						cabStore.update();
					}else {
						mapKey.forEach((key, value) -> {
							if(StrKit.equals("SNO_", value)) {
								if(StrKit.equals("field1", key)) {
									store.setField1(cabStore.getId());
									cabStore.setField1(cabStore.getId());
								}
								if(StrKit.equals("field2", key)) {
									store.setField2(cabStore.getId());
									cabStore.setField2(cabStore.getId());
								}
								if(StrKit.equals("field3", key)) {
									store.setField3(cabStore.getId());
									cabStore.setField3(cabStore.getId());
								}
								if(StrKit.equals("field4", key)) {
									store.setField4(cabStore.getId());
									cabStore.setField4(cabStore.getId());
								}
								if(StrKit.equals("field5", key)) {
									store.setField5(cabStore.getId());
									cabStore.setField5(cabStore.getId());
								}
								cabStore.update();
							}
				        });
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public static void getStoreMapValue(String cabId,String bmbm, Store store) {
		try {
			if (store != null && StrKit.notBlank(store.getId())) {
				List<CabCard> cards = CabCard.dao.find("select * from " + CabCard.TABLE_NAME + " where cabId=? ",cabId);
				if (cards != null && cards.size() > 0) {
					Map<String, String> mapKey = new HashMap<String, String>();
					for (CabCard card : cards) {
						mapKey.put(card.getValue(), card.getCode());
					}
					Record record = null;boolean isofffz = true;
					if(StrKit.equals("53010305", bmbm)) {
						isofffz = false;
						record = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName,t.SName fzyName, "
										+ " (select top 1 convert(varchar(100),EndTime,102) DAlarmEnd from MCabinet where Case_NO = t.SNO_ order by SendTime desc ) DAlarmEnd "
										+ " from [CASE] t where t.SNO_ = '" + store.getId() + "' ");
					}else {
						record = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName from [CASE] t where t.SNO_ = '"+store.getId()+"' ");
					}
					
					if (record != null) {
						String NCase = record.getStr("NId");
						store.setField1(StrKit.isBlank(record.getStr(mapKey.get("field1"))) ? "" : record.getStr(mapKey.get("field1")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField2(StrKit.isBlank(record.getStr(mapKey.get("field2"))) ? "" : record.getStr(mapKey.get("field2")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField3(StrKit.isBlank(record.getStr(mapKey.get("field3"))) ? "" : record.getStr(mapKey.get("field3")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField4(StrKit.isBlank(record.getStr(mapKey.get("field4"))) ? "" : record.getStr(mapKey.get("field4")).replaceAll(" ", "").replaceAll("├─", ""));
						store.setField5(StrKit.isBlank(record.getStr(mapKey.get("field5"))) ? "" : record.getStr(mapKey.get("field5")).replaceAll(" ", "").replaceAll("├─", ""));

						
						if(!isofffz | StrKit.isBlank(record.getStr("DAlarmEnd"))) {
							if(mapKey.containsValue("DAlarmEnd")) {
								mapKey.forEach((key, value) -> {
									if(StrKit.equals("DAlarmEnd", value)) {
										String sqlNormalStr = "select a.SName,a.SIdentityCard,a.NMeasureType,b.DAlarmEnd from Crime a,Stage b where a.NId=b.NCrime "
												+ "	and a.NState <> '-1' and b.NState <> '-1' and b.BisCancle='0' and ( b.BIsPause is null  or b.BIsPause = '0' ) and a.NCase='"+NCase+"' ";
										List<Record> suspectListList=Db.use("plga").find(sqlNormalStr);
										String DAlarmEnd="";
										for(Record suspect:suspectListList) {
											if(!StrKit.isBlank(DAlarmEnd)) {
												SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
												try {
													Date bt=sdf.parse(suspect.getStr("DAlarmEnd"));
													Date et=sdf.parse(DAlarmEnd);
													if(bt.before(et)) {
														DAlarmEnd = suspect.getStr("DAlarmEnd");
													}
												} catch (ParseException e) {
												}
											}else {
												DAlarmEnd = suspect.getStr("DAlarmEnd");
											}
										}
										//赋值
										if(StrKit.equals("field1", key)) {
											store.setField1(DAlarmEnd);
										}
										if(StrKit.equals("field2", key)) {
											store.setField2(DAlarmEnd);
																		}
										if(StrKit.equals("field3", key)) {
											store.setField3(DAlarmEnd);
										}
										if(StrKit.equals("field4", key)) {
											store.setField4(DAlarmEnd);
										}
										if(StrKit.equals("field5", key)) {
											store.setField5(DAlarmEnd);
										}
									}
						        });
							}
						}
					}else {
						mapKey.forEach((key, value) -> {
							if(StrKit.equals("SNO_", value)) {
								if(StrKit.equals("field1", key)) {
									store.setField1(store.getId());
								}
								if(StrKit.equals("field2", key)) {
									store.setField2(store.getId());
								}
								if(StrKit.equals("field3", key)) {
									store.setField3(store.getId());
								}
								if(StrKit.equals("field4", key)) {
									store.setField4(store.getId());
								}
								if(StrKit.equals("field5", key)) {
									store.setField5(store.getId());
								}
							}
				        });
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	
	private static StringBuffer sb;
	public static void handleCrime() {
		try {
			// -------------------------处理已接受嫌疑人-----------------------------
			List<Record> endCrimes = new LinkedList<Record>();
			List<Record> startcrimes = new LinkedList<Record>();
			// 接收表
			String sqlNormalStr = "select a.*,b.SNO_,b.NOfficeId orgId,c.NType,c.DAlarmEnd from Crime a,[Case] b,Stage c where a.NCase=b.NId and a.NId=c.NCrime "
					+ "	and a.NState <> '-1' and b.NState <> '-1' and c.NState <> '-1' and c.BisCancle='0' and ( c.BIsPause is null  or c.BIsPause = '0' ) ";
			List<Record> crimesNormal = Db.use("plga").find(sqlNormalStr);
			for (Record record : crimesNormal) {
				if(StrKit.equals("1", record.getStr("NType")) || StrKit.equals("2", record.getStr("NType")) ||StrKit.equals("3", record.getStr("NType"))) {//拘留
					Record receive = Db.use("plga").findFirst("select * from Stage where NState <> '-1' and NType='83' and SAlarmEndDesc='报捕接收' "
							+ " and BisCancle='0'  and ( BIsPause is null  or BIsPause = '0' )  "
							+ " and NCase='"+record.getStr("NCase")+"' and NCrime='"+record.getStr("NId")+"' ");
					if(receive!=null && StrKit.notBlank(receive.getStr("NId"))) {//已接收
						endCrimes.add(record);
					}else {
						startcrimes.add(record);
					} 
				}else if(StrKit.equals("4", record.getStr("NType")) || StrKit.equals("5", record.getStr("NType")) ||StrKit.equals("6", record.getStr("NType")) 
						|| StrKit.equals("7", record.getStr("NType")) ||StrKit.equals("8", record.getStr("NType"))) {//取保、监居、批捕
//					Record receive = Db.use("plga").findFirst("select * from Stage where NState <> '-1' and NType='93' and SAlarmEndDesc='起诉接收' "
					Record receive = Db.use("plga").findFirst("select * from Stage where NState <> '-1' and NType='93' "
							+ " and BisCancle='0'  and ( BIsPause is null  or BIsPause = '0' )  "
							+ " and NCase='"+record.getStr("NCase")+"' and NCrime='"+record.getStr("NId")+"' ");
					if(receive!=null && StrKit.notBlank(receive.getStr("NId"))) {//已接收
						endCrimes.add(record);
					}else {
						startcrimes.add(record);
					}
				}
			}
			
			//----------------------------处理已接受嫌疑人-------------------------------------
			sb = new StringBuffer();
			Map<String, String> endMap = getCaseStatus(endCrimes, "0");
			endMap.forEach((key, value) -> {
				CabStoreTemp cabStoreTemp = CabStoreTemp.dao
						.findFirst("select * from " + CabStoreTemp.TABLE_NAME + " where type='0' and storeId=? ", key);
				if (cabStoreTemp == null) {
					cabStoreTemp = new CabStoreTemp();
					cabStoreTemp.setId(UuidUtil.getUUID());
					cabStoreTemp.setStoreId(key);
					cabStoreTemp.setType("0");
					cabStoreTemp.save();
				}
				cabStoreTemp.setStatus(value);
				cabStoreTemp.update();
				sb.append("'").append(cabStoreTemp.getStoreId()).append("'").append(",");
			});
			if (!StrKit.isBlank(sb.toString())) {
				Db.delete("delete from " + CabStoreTemp.TABLE_NAME + " where type='0' and  storeId not in (" + (sb.substring(0, sb.length() - 1)) + ") ");
			}
			
			//----------------------------处理未接受嫌疑人-------------------------------------
			sb = new StringBuffer();
			Map<String, String> statrtMap = getCaseStatus(startcrimes, "1");
			statrtMap.forEach((key, value) -> {
				CabStoreTemp cabStoreTemp = CabStoreTemp.dao
						.findFirst("select * from " + CabStoreTemp.TABLE_NAME + " where type='1' and storeId=? ", key);
				if (cabStoreTemp == null) {
					cabStoreTemp = new CabStoreTemp();
					cabStoreTemp.setId(UuidUtil.getUUID());
					cabStoreTemp.setStoreId(key);
					cabStoreTemp.setType("1");
					cabStoreTemp.save();
				}
				cabStoreTemp.setStatus(value);
				cabStoreTemp.update();
				sb.append("'").append(cabStoreTemp.getStoreId()).append("'").append(",");
			});
			
			if (!StrKit.isBlank(sb.toString())) {
				Db.delete("delete from " + CabStoreTemp.TABLE_NAME + " where type='1' and  storeId not in (" + (sb.substring(0, sb.length() - 1)) + ") ");
			}
		} catch (Exception e) {
			log.info("===================Exception============");
			log.info(e.getMessage());
		}
	}

	/**
	 * 
	 * @param crimes
	 * @param type  
	 * -1-超期0-预警1-待审2-正常3-完成
	 */
	public static Map<String, String> getCaseStatus(List<Record> crimes, String type) {

		Map<String, String> caseMap = new HashMap<String, String>();
		for (Record record : crimes) {
			if (DateUtil.getDifferenceForDay(record.getStr("DAlarmEnd")) < 0) {// 超期
				caseMap.put(record.getStr("SNO_"), "-1");
			} else {
				boolean s = false;
				if (ArchiveStage.courtMap.containsKey(record.getInt("NType"))) {
					s = true;
				}
				if (DateUtil.getDifferenceForDay(DateUtil.getrRealDate(record.getStr("DAlarmEnd"), s)) <= 1) {
					caseMap.put(record.getStr("SNO_"), "0");
				}
				
				if (StrKit.equals("0", type)) {// 分局预警
					//分局判判断是否完成
					if(DateUtil.getDifferenceForDay(DateUtil.getrRealDate(record.getStr("DAlarmEnd"), s)) > 1) {
						Record Crime = Db.use("plga").findFirst("select * from Crime where NState <> '-1' and (NMeasureType=82 or NMeasureType=92 ) and NCase='"+record.getStr("NCase")+"' ");
						if(Crime!=null) {
							caseMap.put(record.getStr("SNO_"), "3");
						}
					}
				}else {//派出所预警
				}
				
//				if(StrKit.equals("27", record.getStr("orgId"))) {//经侦
//					boolean s = false;
//					if (ArchiveStage.courtMap.containsKey(record.getInt("NType"))) {
//						s = true;
//					}
//					if (DateUtil.getDifferenceForDay(DateUtil.getrRealDate(record.getStr("DAlarmEnd"), s)) <= 1) {
//						caseMap.put(record.getStr("SNO_"), "0");
//					}
//				}else {
//					if (StrKit.equals("3", record.getStr("NType"))) {
//						if (DateUtil.getDifferenceForDay(DateUtil.getrRealDate(record.getStr("DAlarmEnd"), false)) <= 1) {
//							caseMap.put(record.getStr("SNO_"), "0");
//						}
//					} else {
//						if (StrKit.equals("0", type)) {// 分局预警
//							boolean s = false;
//							if (ArchiveStage.courtMap.containsKey(record.getInt("NType"))) {
//								s = true;
//							}
//							if (DateUtil.getDifferenceForDay(DateUtil.getrRealDate(record.getStr("DAlarmEnd"), s)) <= 1) {
//								caseMap.put(record.getStr("SNO_"), "0");
//							}else {
//								//分局判判断是否完成
//								Record Crime = Db.use("plga").findFirst("select * from Crime where NState <> '-1' and (NMeasureType=82 or NMeasureType=92 ) and NCase='"+record.getStr("NCase")+"' ");
//								if(Crime!=null) {
//									caseMap.put(record.getStr("SNO_"), "3");
//								}
//							}
//						} else {// 派出所预警
//							if (StrKit.equals("1", record.getStr("NType"))) {// 拘留7天,提前三天预警
//								if (DateUtil.getDifferenceForDay(record.getStr("DAlarmEnd")) <= 3) {
//									caseMap.put(record.getStr("SNO_"), "0");
//								}
//							}
//							if (StrKit.equals("2", record.getStr("NType"))) {// 拘留30天，提前10天预警
//								if (DateUtil.getDifferenceForDay(record.getStr("DAlarmEnd")) <= 10) {
//									caseMap.put(record.getStr("SNO_"), "0");
//								}
//							}
//							if (StrKit.equals("6", record.getStr("NType")) || StrKit.equals("7", record.getStr("NType"))) {// 监视居住
//								if (DateUtil.getDifferenceForDay(record.getStr("DAlarmEnd")) <= 30 * 2) {
//									caseMap.put(record.getStr("SNO_"), "0");
//								}
//							}
//							if (StrKit.equals("8", record.getStr("NType"))) {// 批捕
//								if (DateUtil.getDifferenceForDay(record.getStr("DAlarmEnd")) <= 30) {
//									caseMap.put(record.getStr("SNO_"), "0");
//								}
//							}
//							if (StrKit.equals("4", record.getStr("NType"))
//									|| StrKit.equals("5", record.getStr("NType"))) {// 取保候审
//								if (DateUtil.getDifferenceForDay(record.getStr("DAlarmEnd")) <= 30 * 6) {
//									caseMap.put(record.getStr("SNO_"), "0");
//								}
//							}
//						}
//					}
//				}
			}
		}
		return caseMap;
	}

	// 授权短信通知
//	public static void sendAuthSms (Auth auth,GrantUser grantUser,List<CabinetAuth> cabinetOldAuth,String type,String authType) {
//		new Thread(()->{
//			Cabinet cabinet=Cabinet.findByAuth(auth.getLicense());
//			if(cabinet!=null) {
//				SysOrg sysOrg=SysOrg.dao.findById(cabinet.getOrgId());
//				String zbTel = "",jbTel="",userIds="",SendType="",userNames="",content="",zbContent="",jbContent="",SName="",zbcontent="";
//				String dateStr = DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss");
//				if(StrKit.equals(type, "add")) {
//					String[] arr = grantUser.getAuthUsers().split("\\|");
//					for (String r : arr) {
//						if (!StrKit.isBlank(r)) {
//							userIds += "'"+r+"',";
//						}
//					}
//					userIds = userIds.substring(0, userIds.length()-1);
//					SendType = "添加";
//					zbContent = "【云南公安短信平台】【盘龙法制】您好！"+grantUser.getCaseNo()+"号案件的存取权限，已于"+dateStr+"分配给";
//					jbContent = "【云南公安短信平台】【盘龙法制】"+grantUser.getCaseNo()+"号案件的存取权限，已于"+dateStr+"开通成功！";
//				}else {
//					for (CabinetAuth cabinetAuth : cabinetOldAuth) {
//						userIds += "'"+cabinetAuth.getUseName()+"',";
//					}
//					userIds = userIds.substring(0, userIds.length()-1);
//					SendType = "取消";
//					content = "【云南公安短信平台】【盘龙法制】您好！"+grantUser.getCaseNo()+"号案件的存取权限，已于"+DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss")+"取消。";
//					if(StrKit.equals(authType, "all")) {
//						String sqlPara = "";
//						String uId = "";
//						sqlPara = "select a.id, a.name,a.username,a.zp,a.tempRoleKey "
//								+ " from sys_user a where a.username!=? and a.id in(  select  user_id from sys_user_role where role_id in "
//								+ " (select t.id from sys_role t where t.key like 'Cabinet-%' and t.key not like '%Leader%' and t.key not like '%Manage%' ) ) "
//								+ "and id in (SELECT user_id from sys_user_org where org_id in "
//								+ " (select org_id from biz_cabinet where auth=? )) and a.username not in ("+userIds+") ";
//						List<SysUser> userList = SysUser.dao.find(sqlPara, grantUser.getUsername(), auth.getLicense());
//						for (SysUser u: userList) {
//							uId += "'"+u.getUsername()+"',";
//						}
//						userIds = uId.substring(0, uId.length()-1);
//					}
//				}
//				
//				if(sysOrg!=null && StrKit.equals("530103",sysOrg.getCode())) {
//					Record record=Db.use("plgaj").findFirst("select STel,SName from Manage where SIdentityCard=? ",grantUser.getUsername());
//					List<Record> records=Db.use("plgaj").find("select STel,SName from Manage where SIdentityCard in ("+userIds+") ");
//					if(record!=null) {
//						zbTel = record.getStr("STel")+",";
//						SName= record.getStr("SName");
//					}
//					for (Record rec : records) {
//						jbTel += rec.getStr("STel")+",";
//						userNames += rec.getStr("SName")+",";
//					}
//					jbContent = "【云南公安短信平台】【盘龙法制】您好！"+grantUser.getCaseNo()+"号案件，已于"+dateStr+"由"+SName+"授权您负责审核，请及时处理。";
//				}else {
//					SysUser zbUser=SysUser.dao.findFirst("SELECT lxdh,name FROM "+SysUser.tableName+" WHERE username=? ",grantUser.getUsername());
//					List<SysUser> list=SysUser.dao.find("SELECT lxdh,name FROM "+SysUser.tableName+" WHERE username in ("+userIds+") ");
//					if(zbUser!=null) {
//						zbTel = zbUser.getLxdh();
//						SName= zbUser.getName();
//					}
//					for (SysUser user : list) {
//						jbTel += user.getLxdh()+",";
//						userNames += user.getName()+",";
//					}
//				}
//				zbcontent = "【云南公安短信平台】【盘龙法制】您好！"+grantUser.getCaseNo()+"号案件,"+userNames+"的存取权限，已于"+DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss")+"被您取消。";
//				//发送主办人短息
//				Map<String, Object> caseMap  = new HashMap<String, Object>();
//				caseMap.put("STel", zbTel);
//				caseMap.put("SendType", "主办人"+SendType+"授权");
//				caseMap.put("content", StrKit.equals(type, "add")?zbContent+userNames.substring(0, userNames.length()-1)+"。":zbcontent);
//				//Result resultZb= null;
//				Result resultZb = HttpUtil.doPostForForm(HttpUtil.CASE_HTTP_URL + "/sendSMS.ashx",caseMap);
//				System.out.println("=======主办人添加授权===="+JsonKit.toJson(resultZb));
//				
//				//发送经办人短信
//				caseMap.clear();
//				caseMap.put("STel", jbTel);
//				caseMap.put("SendType", "主办人"+SendType+"授权");
//				caseMap.put("content", StrKit.equals(type, "add")?jbContent:content);
//				//Result resultJb=null;
//				HttpUtil.doPostForForm(HttpUtil.CASE_HTTP_URL + "/sendSMS.ashx",caseMap);
//			}
//        }).start(); 
//	}
}
